package com.kzw.core.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.prefs.Preferences;

import de.schlichtherle.license.CipherParam;
import de.schlichtherle.license.KeyStoreParam;
import de.schlichtherle.license.LicenseContent;
import de.schlichtherle.license.LicenseManager;
import de.schlichtherle.license.LicenseParam;

public class LicenseUtil {

	private static final String CIPHER_KEY_PWD = "hello123";
	private static final String KEYSTORE_PWD = "hello123";
	private static final String ALIAS = "publickey";
	private static final String SUBJECT = "yunwei";
	private static final String PUB_RESOURCE = "/license/public.store";
	private static final String LIC_RESOURCE = "/license/license.lic";
	private static final String MENU_RESOURCE = "/license/license.dat";

	private static final KeyStoreParam publicKeyStoreParam = new KeyStoreParam() {
		public InputStream getStream() throws IOException {
			return LicenseUtil.class.getResourceAsStream(PUB_RESOURCE);
		}

		public String getAlias() {
			return ALIAS;
		}

		public String getStorePwd() {
			return KEYSTORE_PWD;
		}

		public String getKeyPwd() {
			return null;
		}
	};

	private static final CipherParam cipherParam = new CipherParam() {
		public String getKeyPwd() {
			return CIPHER_KEY_PWD;
		}
	};
	private static final LicenseParam licenseParam = new LicenseParam() {
		public String getSubject() {
			return SUBJECT;
		}

		public Preferences getPreferences() {
			return Preferences.userNodeForPackage(LicenseUtil.class);
		}

		public KeyStoreParam getKeyStoreParam() {
			return publicKeyStoreParam;
		}

		public CipherParam getCipherParam() {
			return cipherParam;
		}

	};

	public static LicenseContent install() {
		LicenseManager lm = new LicenseManager(licenseParam);
		try {
			String licFilename = LicenseUtil.class.getResource(LIC_RESOURCE).toURI().getPath();
			File licenseFile = new File(licFilename);
			String menuFilename = LicenseUtil.class.getResource(MENU_RESOURCE).toURI().getPath();
			File menuFile = new File(menuFilename);
			lm.install(licenseFile, menuFile);
			return lm.verify();
		} catch (Exception e) {
			// e.printStackTrace();
			return null;
		}
	}

	/**
	 * 验证是否有效
	 */
	public static void validate() {
		LicenseManager lm = new LicenseManager(licenseParam);
		try {
			String licFilename = LicenseUtil.class.getResource(LIC_RESOURCE).toURI().getPath();
			File licenseFile = new File(licFilename);
			lm.install(licenseFile);
			lm.validate();
		} catch (Exception e) {
			// e.printStackTrace();
			System.exit(1);
		}
	}

}
